<?
    class SpaController extends Principio_Library_ControllerAction
    {
        public function init()
        {
            parent::init();
            $this->view->menu = array(
                "Edit" => "edit",
                "Attendant Console" => "console",
                "Custom Template" => "customize",
                "View Full Profile" => "fullprofile",
                "Delete" => "delete"
                );
	    }

        public function fullprofileAction()
        {
            if (($this->is_post) && ($this->checkPostItemInt("id", "SPA ID")))
            {
                $model_spa = Principio_Model_SpaMapper::get($this->post_data['id']);

                $config_principio = Zend_Registry::get("config_principio");
                $request_string = "http://".$config_principio['hostname']."/prv?mac=".rawurlencode($model_spa->getMAC())."&s_id=".rawurlencode($model_spa->getSerial())."&s=9&ip=".rawurlencode($model_spa->getIP());
                $response_string = file_get_contents($request_string);
                $response_string = str_replace("<", "&lt;", $response_string);
                $response_string = str_replace(">", "&gt;", $response_string);
                $this->view->title = "Full Profile";
                $this->view->fullprofile = $response_string;
            };
        }


        private function checkUnique($field, $public_field)
        {
            $model_company = Principio_Model_SpaMapper::checkUnique($this->post_data, $field);
            if ($model_company !== false)
                Principio_Library_Common::reportValidationFails("Device with ".$public_field." [".$this->post_data[$field]."] already exists in a company [".$model_company->getCaption()."]");
        }


        private function validate()
        {
            if ($this->checkPostItemString("mac", "MAC"))
            {
                $this->view->model_spa->setMAC($this->post_data['mac']);
                if (Principio_Library_Common::checkValidity(preg_match("/^(([[:xdigit:]]){2}:){5}([[:xdigit:]]){2}$/", $this->post_data['mac']), "MAC has to be in XX:XX:XX:XX:XX:XX format"))
                    $this->checkUnique("mac", "MAC");
            };

            if ($this->checkPostItemString("serial", "S/N"))
            {
                $this->view->model_spa->setSerial($this->post_data['serial']);
                $this->checkUnique("serial", "serial");
            };

            if ($this->checkPostItemIP("ip", "IP"))
            {
                $this->view->model_spa->setIP($this->post_data['ip']);
                $this->checkUnique("ip", "IP");
            };


            for ($i = 0; $i < $this->view->model_spa->getModelType()->getExts(); $i++)
            {
                if (Principio_Library_Common::checkValidity(isset($this->post_data['ext'.$i]) && ( (intval($this->post_data['ext'.$i]) > 0) || (intval($this->post_data['ext'.$i]) == -1)), "Ext ".$i." is empty" ))
                    $this->view->model_spa->setModelAccount($i, Principio_Model_AccountMapper::get(intval($this->post_data['ext'.$i])));
            };


            $this->loadAccounts();

            return !Principio_Library_Common::$is_error;
        }


        private function loadAccounts($is_blank = false)
        {
            $this->view->accounts = array();

            if (!$is_blank)
            {
                for ($i = 0; $i < $this->view->model_spa->getModelType()->getExts(); $i++)
                {
                    $company_id = $this->view->model_spa->getModelAccount($i)->getCompanyID();
                    if (!isset($this->view->accounts[$company_id]))
                    {
                        if ($company_id == -1)
                            $this->view->accounts[$company_id] = (isset($this->view->accounts[$this->view->model_spa->getCompanyID()]))
                                                                ? $this->view->accounts[$this->view->model_spa->getCompanyID()]
                                                                : Principio_Model_AccountMapper::getInCompany($this->view->model_spa->getCompanyID());
                        else
                            $this->view->accounts[$company_id] = Principio_Model_AccountMapper::getInCompany($company_id);
                    };
                };
            }
            else
                $this->view->accounts[-1] = Principio_Model_AccountMapper::getInCompany($this->view->model_spa->getCompanyID());
        }


        public function editAction()
        {
            if (($this->is_post) && ($this->checkPostItemInt("id", "SPA ID")))
            {
                $this->view->is_add = false;
                $this->view->model_spa = Principio_Model_SpaMapper::get($this->post_data['id']);

                if ($this->is_apply)
                {
                    if ($this->validate())
                    {
                        if (Principio_Model_SpaMapper::save($this->view->model_spa))
                        {
                            Principio_Library_Common::$msg = "SPA was updated.";
                            Principio_Library_DHCP::generate();
                        };
                    };
                }
                else
                    $this->loadAccounts();

                $this->view->companies = Principio_Model_CompanyMapper::getByType(Principio_Model_CompanyMapper::TYPE_COMPANY);

                // SPA in a pool
                if (!isset($this->view->companies[$this->view->model_spa->getCompanyID()]))
                    $this->view->model_company = Principio_Model_CompanyMapper::get($this->view->model_spa->getCompanyID());
                else
                    $this->view->model_company = $this->view->companies[$this->view->model_spa->getCompanyID()];

                $this->view->ip_not_in_use = Principio_Model_SpaMapper::getIpNotInUse($this->view->model_spa->getCompanyID(), $this->view->model_spa->getIP());
                $this->view->title = "View and edit ".$this->view->model_spa->getModelType()->getCaption()." device";
            }
        }
	
        public function customizeAction()
        {
            if ($this->is_post)
            {
                if ($this->checkPostItemInt("id", "SPA ID"))
                {
                    $model_spa = Principio_Model_SpaMapper::get($this->post_data['id']);

                    if ($this->is_apply)
                    {
                        $model_spa_ext_template = new Principio_Model_SpaExtTemplates($model_spa->getModelType()->getExts());
                        $model_spa_ext_template->setSpaID($model_spa->getID());
                        for ($i = 0; $i <= $model_spa->getModelType()->getExts(); $i++)
                        {
                            if (isset($this->post_data["ext".$i."_template"]))
                                $model_spa_ext_template->setTemplate($i, $this->post_data["ext".$i."_template"]);
                            else
                                $model_spa_ext_template->setTemplate($i, "");
                        };

                        Principio_Model_SpaExtTemplatesMapper::update($model_spa_ext_template);
                        Principio_Library_Common::$msg = "Templates were updated.";
                    };

                    $this->view->model_spa_ext_templates = Principio_Model_SpaExtTemplatesMapper::get($model_spa->getID());
                };
            };
        }


	    public function addAction()
	    {
            if ($this->is_post) 
            {
                if ( ($this->checkPostItemInt("company_id", "Company ID")) && ($this->checkPostItemInt("type_id", "Type ID")))
                {
                    $this->view->is_add = true;
                    $this->view->model_spa = new Principio_Model_Spa(Principio_Model_TypeMapper::get($this->post_data["type_id"]));
                    $this->view->model_spa->setCompanyID($this->post_data['company_id']);
                    $this->post_data['id'] = -1;

                    if ($this->is_apply)
                    {
                        if ($this->validate())
                        {
                            if (Principio_Model_SpaMapper::save($this->view->model_spa) !== false)
                            {

                                $this->view->is_add = false;
                                Principio_Library_Common::$msg = "Device was added.";
                                $this->view->title = "View & Edit ".$this->view->model_spa->getModelType()->getCaption()." device";
                                Principio_Library_DHCP::generate();
                            };
                        };
                    }
                    else
                        $this->loadAccounts(true);


                    $this->view->ip_not_in_use = Principio_Model_SpaMapper::getIpNotInUse($this->view->model_spa->getCompanyID(), ($this->view->model_spa->getIP() == "" ? null : $this->view->model_spa->getIP()));
                    $this->view->companies = Principio_Model_CompanyMapper::getByType(Principio_Model_CompanyMapper::TYPE_COMPANY);

                    // SPA in a pool
                    if (!isset($this->view->companies[$this->view->model_spa->getCompanyID()]))
                        $this->view->model_company = Principio_Model_CompanyMapper::get($this->view->model_spa->getCompanyID());
                    else
                        $this->view->model_company = $this->view->companies[$this->view->model_spa->getCompanyID()];

                    $this->view->title = "Add new device";

                };
            };
	    }
	
        
        public function adddeviceAction()
        {
            if ( ($this->is_post) && ($this->checkPostItemInt("company_id", "Company ID")))
            {
                $this->view->title = "Add new spa type device";
                $this->view->types = Principio_Model_TypeMapper::get();
                $this->view->company_id = $this->post_data['company_id'];
            };
        }
	
        
        public function deleteAction()
        {
            if ( ($this->is_post) && ($this->checkPostItemInt("id", "SPA ID")))
            {
                if (Principio_Model_SpaMapper::delete(Principio_Model_SpaMapper::get($this->post_data['id'])))
                {
                    Principio_Library_DHCP::generate();
                    Principio_Library_Common::$msg = "SPA was deleted.";
                };
            };
        }
}